package com.drcoffee.drcoffeemall.filter;

import com.drcoffee.drcoffeemall.entry.ExceptionRecord;
import com.drcoffee.drcoffeemall.service.UserService;
import com.drcoffee.drcoffeemall.service.impl.UserServiceImpl;
import com.drcoffee.drcoffeemall.util.LllegalRequestUtil;
import com.drcoffee.drcoffeemall.util.SpringUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.*;

@Slf4j
@WebFilter("/*")
public class TokenFilter extends OncePerRequestFilter {

    private UserService userService;

    private static final List<String> excludedPaths = Arrays.asList(
            "/user/login",
            "/user/accountLogin",
            "/user/codeLogin",
            "/user/sendLoginCode",
            "/user/verifyAccount",
            "/user/register",
            "/user/addAddress",
            "/user/removeToken",
            "/user/sebdEmailCode",
            "/user/verifyEmailCode",
            "/user/verifyToken",
            "/user/isExist",
            "/user/haveRegistered",
            "/user/sendRePassCode",
            "/user/retrievePass",
            "/user/setAccount",
            "/user/invitationCheck",
            "/user/sendPhoneCode",
            "/user/verifyCode",
            "/pay/payOne",
            "/pay/aliPay",
            "/pay/notify",
            "/pay/return",
            "/wechatPay/notify",
            "/wechatPay/notifyRefund",
            "/file/",
            "/user/sendEmailCode",
            "/WW_verify_eZvr7YJup261Oino.txt",
            "/imserver/*",
            "/"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
//        System.out.println("66666666666666666666666666"+request.getHeader("token"));
        String requestURI = request.getRequestURI();
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        String private_ip = request.getRemoteAddr();
        log.info("请求路径：" + requestURI);
        log.info("请求方式：" + request.getMethod());
        log.info("公网IP：" + xForwardedFor);
        log.info("客户端IP：" + private_ip);
        String ip = null;
        if (xForwardedFor != null) {
            String[] ips = xForwardedFor.split(",");
            ip = ips[0].trim();
        }
        ExceptionRecord exceptionRecord = LllegalRequestUtil.processData(requestURI, ip, private_ip);
//        if (isExcludedPath(requestURI) || isOptionsMethod(request) || isLocalRequest(request) || private_ip.equals("172.66.2.80")) {
        if (isExcludedPath(requestURI) || isOptionsMethod(request) || isLocalRequest(request)) {
            filterChain.doFilter(request, response);
        } else {
            String token = request.getHeader("Token");
            if (isValidToken(token, exceptionRecord)) {
                // Token有效，继续处理请求
                log.info("===================== Token有效 =====================");
                userService.renewalToken(token);
                filterChain.doFilter(request, response);
            } else {
                log.warn("===================== Token无效 =====================");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                response.setHeader("Access-Control-Allow-Origin", "*");
            }
        }
    }

    private boolean isExcludedPath(String path) {
//        return excludedPaths.stream().anyMatch(path::endsWith);
        return  true;
    }


    private boolean isOptionsMethod(HttpServletRequest request) {
        return "OPTIONS".equals(request.getMethod());
    }

    private boolean isLocalRequest(HttpServletRequest request) {
        return "127.0.0.1".equals(request.getRemoteHost());
    }

    private boolean isValidToken(String token, ExceptionRecord exceptionRecord) {
        if (userService == null) {
            this.userService = SpringUtils.getBean(UserServiceImpl.class);
        }
        return userService.verifyToken(token, exceptionRecord);
    }
}
